package com.yitianyigexiangfa.netty.custom.string.protocol.codec;

import com.yitianyigexiangfa.netty.custom.string.protocol.bean.LuckHeader;
import com.yitianyigexiangfa.netty.custom.string.protocol.bean.LuckMessage;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.EmptyByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

public class LuckDecoder extends ByteToMessageDecoder {

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        if (in.readableBytes() < 5) {
            return;
        }
        int version = in.readInt();
        int contentLength = in.readInt();
        byte[] sessionByte = new byte[36];
        in.readBytes(sessionByte);
        String sessionId = new String(sessionByte);

        LuckHeader header = new LuckHeader(version, contentLength,sessionId);

        String content = new String(in.readBytes(in.readableBytes()).array());
//        byte[] contents = new byte[contentLength];
//        in.readBytes(contents);
//        String content = new String(contents);

        LuckMessage message = new LuckMessage(header, content);
        out.add(message);
    }
}
